<template>
  <div class="entrust-list-container">
    <div class="page-header">
      <div class="header-title">
        <h2>案件分案列表<span>（{{ totalCasesCount }}条数据）</span></h2>
        <p class="date-range-info">
          显示待分案案件数据，按批次分组显示
        </p>
      </div>
      <div class="header-actions">
        <a-button @click="handleRefresh">
          <span>刷新</span>
        </a-button>
        <a-button type="primary" :disabled="isEntrustButtonDisabled" @click="handleEntrust">
          <span> 分案</span>
        </a-button>
      </div>
    </div>

    <!-- 新布局：侧边栏 + 主内容区域 -->
    <div class="new-layout">
      <!-- 侧边栏 -->
      <div v-if="currentTableData.length > 0" class="w-1/5 h-full pr-5 sticky-sidebar">
        <a-card class="h-full position-relative" type="inner" :body-style="{ padding: '20px' }"
          style="margin-bottom: 24px; box-shadow: none;">

          <a-menu style="width: 100%" mode="vertical" :selected-keys="[activeTabKey]" @click="handleMenuClick"
            :items="menuItems">
            <template #item="{ key, label }">
              <div class="menu-item-wrapper">
                <a-checkbox 
                  v-if="key === 'select-all'"
                  :checked="isAllBatchesSelected"
                  @change="handleMenuClick({ key: 'select-all' })"
                  class="menu-checkbox"
                />
                <a-checkbox 
                  v-else-if="key !== 'no-data'"
                  :checked="selectedBatches.includes(key)"
                  @change="handleMenuClick({ key })"
                  class="menu-checkbox"
                />
                <span class="menu-label">{{ label }}</span>
              </div>
            </template>
          </a-menu>

        </a-card>
      </div>

      <!-- 主内容区域 -->
      <div class="w-4/5 h-full overflow-auto">
        <a-spin :spinning="loading" tip="加载中...">
          <!-- 无数据时显示 -->
          <div v-if="currentTableData.length === 0 && !loading" class="no-data-container">
            <a-empty style="margin-top: 100px;" image="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg"
              :image-style="{ height: '120px', display: 'flex', flexDirection: 'column', alignItems: 'center' }">
              <template #description>
                <span class="empty-description">暂无分案案件数据</span>
                <p class="empty-tip">今日暂无待分案的案件，请稍后再试或联系管理员</p>
              </template>
            </a-empty>
          </div>

          <!-- 有数据时显示表格 -->
          <a-table :bordered="true" v-else :columns="columns" :data-source="currentTableData" :pagination="false"
            :row-selection="rowSelection" row-key="loanId" :scroll="{ y: 'calc(100vh - 300px)' }" size="small">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'customerInfo'">
                <div class="customer-info">
                  <div class="customer-name">{{ record.realName }}</div>
                  <div class="customer-mobile">{{ record.mobile }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'amountInfo'">
                <div class="amount-info">
                  <div>待还金额：{{ formatAmount(record.totalNoRepayRepay) }}</div>
                  <div>实还金额：{{ formatAmount(record.realBackedRepay) }}</div>
                  <div>减免金额：{{ formatAmount(record.mitigateBackedRepay) }}</div>
                </div>
              </template>
              <template v-else-if="column.key === 'lastRepayDate'">
                {{ formatDate(record.lastBackedDate) }}
              </template>
              <template v-else-if="column.key === 'projectStatus'">
                <Tag :color="getProjectStatusColor(record.state)">
                  {{ getProjectStatusText(record.state) }}
                </Tag>
              </template>
              <template v-else-if="column.key === 'distributeStatus'">
                <Tag :color="getDistributeStatusColor(record.distributeState)">
                  {{ getDistributeStatusText(record.distributeState) }}
                </Tag>
              </template>
            </template>
          </a-table>
        </a-spin>
      </div>
    </div>


    <div class="affix-container" v-if="casesData.length > 0">
      <a-space align="center">
        <!-- 当前步骤操作按钮 -->
        <div class="step-actions">

        </div>
      </a-space>
    </div>

    <!-- 分案弹框 -->
    <a-modal v-model:open="isEntrustModalVisible" title="分案" width="600px" :ok-text="'提交'" :cancel-text="'取消'"
      @ok="handleEntrustConfirm" @cancel="handleEntrustCancel">
      <a-form :model="entrustForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <!-- 符合规则人数 -->
        <a-form-item label="符合规则人数">
          <a-input :value="entrustForm.validClients" :disabled="true" style="width: 100%" />
        </a-form-item>

        <!-- 案件数量 -->
        <a-form-item label="案件数量">
          <a-input :value="entrustForm.caseCount" :disabled="true" style="width: 100%" />
        </a-form-item>

        <!-- 不符合规则警告 -->
        <a-form-item v-if="entrustForm.errClient > 0" :wrapper-col="{ span: 24 }">
          <a-alert
            :message="`选中案件所对应的客户中，有${entrustForm.errClient}个不符合分案规则，如确定，该${entrustForm.errClient}个客户将不会被分出，符合规则的客户仍可继续分案，请问是否确定？`"
            type="warning" show-icon style="margin-top: 8px;" />
        </a-form-item>

        <!-- 组织架构 -->
        <a-form-item label="组织架构" :rules="[{ required: true, message: '请选择组织架构' }]">
          <a-select v-model:value="entrustForm.orgId" placeholder="请选择组织架构" style="width: 100%"
            @change="handleOrgChange">
            <a-select-option v-for="item in orgList" :key="item.id" :value="item.id">
              {{ item.orgName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 组织人员 -->
        <a-form-item label="组织人员" :rules="[{ required: true, message: '请选择组织人员' }]">
          <a-select v-model:value="entrustForm.targetIds" placeholder="请选择组织人员" style="width: 100%" mode="multiple"
            :disabled="!entrustForm.orgId">
            <a-select-option v-for="item in userList" :key="item.userId" :value="item.userId">
              {{ item.realName }} ({{ item.accountNo }})
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { message, Tag } from 'ant-design-vue';
import { getCaseList, countDistributeOne, getOrgList, queryUserByOrg, distributeOne } from '../server/api';
import type { GetCaseListParams, CaseRecord } from '../server/type';
import { useScheduledTask } from '../composables/useScheduledTask';
import dayjs from 'dayjs';

// 案件数据
const casesData = ref<CaseRecord[]>([]);
const activeTabKey = ref<string>('');

// 批次选择状态
const selectedBatches = ref<string[]>([]);
const isAllBatchesSelected = ref(false);

// 表格列配置
const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    customRender: ({ index }: { index: number }) => {
      return index + 1;
    }
  },
  {
    title: '客户LoanId',
    dataIndex: 'loanId',
    key: 'loanId',
    width: 150,
    align: 'center'
  },
  {
    title: '借钱项目产品线',
    dataIndex: 'productTypeName',
    key: 'productTypeName',
    width: 150,
    align: 'center'
  },
  {
    title: '客户信息',
    key: 'customerInfo',
    width: 150,
    align: 'center'
  },
  {
    title: '项目编号批次',
    dataIndex: 'batchName',
    key: 'batchName',
    width: 150,
    align: 'center'
  },
  {
    title: '案件编号',
    dataIndex: 'loanNo',
    key: 'loanNo',
    width: 150,
    align: 'center'
  },
  {
    title: '待还金额实还/减免金额',
    key: 'amountInfo',
    width: 200,
    align: 'center'
  },
  {
    title: '首次入库最后还款',
    key: 'urgeTime',
    width: 150,
    align: 'center',
    customRender: ({ record }: { record: any }) => {
      return record.urgeTime ? dayjs(record.urgeTime).format('YYYY-MM-DD HH:mm:ss') : '-';
    }
  },
  {
    title: '项目状态',
    key: 'projectStatus',
    width: 120,
    align: 'center'
  },
  {
    title: '分案状态',
    key: 'distributeStatus',
    width: 120,
    align: 'center'
  }
];

// 行选择配置
const selectedRowKeys = ref<string[]>([]);
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (selectedKeys: string[]) => {
    selectedRowKeys.value = selectedKeys;
    // 检查是否全选当前显示的数据
    const currentData = currentTableData.value;
    isEntrustButtonDisabled.value = selectedKeys.length !== currentData.length || selectedKeys.length === 0;
  },
  onSelectAll: (selected: boolean, selectedRows: CaseRecord[], changeRows: CaseRecord[]) => {
    console.log('全选状态:', selected, '选中的行:', selectedRows, '变化的行:', changeRows);
    const currentData = currentTableData.value;
    isEntrustButtonDisabled.value = !selected || currentData.length === 0;
  }
};

// 分案相关状态
const isEntrustModalVisible = ref(false);
const isEntrustButtonDisabled = ref(true);
const entrustForm = ref({
  validClients: 0, // 符合规则人数
  caseCount: 0, // 案件数量
  errClient: 0, // 不符合规则人数
  orgId: '', // 组织架构ID
  targetIds: [] as string[], // 组织人员ID列表
  channelClients: [] as any[], // 渠道客户信息
  loanIds: [] as string[] // 选中的案件ID列表
});
const orgList = ref<any[]>([]); // 组织架构列表
const userList = ref<any[]>([]); // 组织人员列表

// 加载状态
const loading = ref(false);

// 定时任务composables
const { executeTask: executeScheduledTask } = useScheduledTask();


// 按批次分组的数据
const groupedCases = computed(() => {
  const groups: Record<string, CaseRecord[]> = {};
  casesData.value.forEach(caseItem => {
    const batchName = caseItem.batchName || '未分组';
    if (!groups[batchName]) {
      groups[batchName] = [];
    }
    groups[batchName].push(caseItem);
  });

  // 对每个批次内的数据进行排序，待审核的放到最前面
  Object.keys(groups).forEach(batchName => {
    groups[batchName].sort((a, b) => {
      // 获取状态码进行比较
      const getStateCode = (state: any) => {
        if (typeof state === 'object' && state.code) {
          return state.code;
        }
        return typeof state === 'string' ? state : '';
      };

      const stateA = getStateCode(a.state);
      const stateB = getStateCode(b.state);

      // 待审核状态优先
      if (stateA === 'PENDING_AUDIT' && stateB !== 'PENDING_AUDIT') return -1;
      if (stateB === 'PENDING_AUDIT' && stateA !== 'PENDING_AUDIT') return 1;

      // 其他状态按原有顺序
      return 0;
    });
  });

  return groups;
});

// 生成侧边栏菜单项
const menuItems = computed(() => {
  const batchNames = Object.keys(groupedCases.value);
  
  // 添加全选选项
  const items = [
    {
      key: 'select-all',
      label: `全选 (${casesData.value.length}条)`,
      title: '全选所有批次',
      type: 'checkbox'
    },
    ...batchNames.map(batchName => ({
      key: batchName,
      label: `${batchName} (${groupedCases.value[batchName].length}条)`,
      title: batchName,
      type: 'checkbox'
    }))
  ];

  // 如果没有数据，显示默认项
  if (batchNames.length === 0) {
    return [{
      key: 'no-data',
      label: '暂无数据',
      title: '暂无数据'
    }];
  }

  return items;
});

// 当前显示的数据
const currentTableData = computed(() => {
  if (activeTabKey.value === 'multiple') {
    // 多批次选择时显示所有选中批次的数据
    return allSelectedBatchesData.value;
  } else if (activeTabKey.value && groupedCases.value[activeTabKey.value]) {
    return groupedCases.value[activeTabKey.value];
  }
  return [];
});

// 所有选中批次的数据
const allSelectedBatchesData = computed(() => {
  if (selectedBatches.value.length === 0) {
    return [];
  }
  
  const allData: CaseRecord[] = [];
  selectedBatches.value.forEach(batchName => {
    if (groupedCases.value[batchName]) {
      allData.push(...groupedCases.value[batchName]);
    }
  });
  
  return allData;
});

// 总案件数量
const totalCasesCount = computed(() => {
  return casesData.value.length;
});


// 格式化金额
const formatAmount = (amount: number) => {
  if (amount === null || amount === undefined) return '0.00';
  return (amount / 100).toFixed(2);
};

// 格式化日期
const formatDate = (date: string | number | null) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD');
};

// 获取项目状态文本
const getProjectStatusText = (state: any) => {
  if (typeof state === 'object' && state.message) {
    return state.message;
  }
  return typeof state === 'string' ? state : '未知';
};

// 获取项目状态颜色
const getProjectStatusColor = (state: any) => {
  let statusCode = state;
  if (typeof state === 'object' && state.code) {
    statusCode = state.code;
  }
  const colorMap: Record<string, string> = {
    'INIT': 'blue',
    'PROCESSING': 'processing',
    'COMPLETED': 'success',
    'FAILED': 'error',
    'CANCELLED': 'default'
  };
  return colorMap[statusCode] || 'default';
};

// 获取分案状态文本
const getDistributeStatusText = (distributeState: any) => {
  if (typeof distributeState === 'object' && distributeState.message) {
    return distributeState.message;
  }
  return typeof distributeState === 'string' ? distributeState : '未知';
};

// 获取分案状态颜色
const getDistributeStatusColor = (distributeState: any) => {
  let statusCode = distributeState;
  if (typeof distributeState === 'object' && distributeState.code) {
    statusCode = distributeState.code;
  }
  const colorMap: Record<string, string> = {
    'UNASSIGNED': 'orange',
    'ASSIGNED': 'blue',
    'IN_PROGRESS': 'processing',
    'COMPLETED': 'success',
    'CANCELLED': 'default'
  };
  return colorMap[statusCode] || 'default';
};


// 处理侧边栏菜单点击
const handleMenuClick = ({ key }: { key: string }) => {
  if (key === 'no-data') {
    return;
  }
  
  if (key === 'select-all') {
    // 全选/取消全选
    if (isAllBatchesSelected.value) {
      selectedBatches.value = [];
      isAllBatchesSelected.value = false;
    } else {
      selectedBatches.value = Object.keys(groupedCases.value);
      isAllBatchesSelected.value = true;
    }
  } else {
    // 单个批次选择
    const batchIndex = selectedBatches.value.indexOf(key);
    if (batchIndex > -1) {
      selectedBatches.value.splice(batchIndex, 1);
    } else {
      selectedBatches.value.push(key);
    }
    
    // 更新全选状态
    isAllBatchesSelected.value = selectedBatches.value.length === Object.keys(groupedCases.value).length;
  }
  
  // 更新表格显示数据
  if (selectedBatches.value.length === 1) {
    activeTabKey.value = selectedBatches.value[0];
  } else if (selectedBatches.value.length > 1) {
    activeTabKey.value = 'multiple';
  } else {
    activeTabKey.value = '';
  }
  
  // 清空复选框
  selectedRowKeys.value = [];
  isEntrustButtonDisabled.value = true;
};


// 获取分案案件列表数据
const fetchEntrustList = async () => {
  loading.value = true;
  try {
    // 获取今日开始和结束时间
    const today = dayjs();
    const todayStart = today.startOf('day').toISOString();
    const todayEnd = today.endOf('day').toISOString();

    const defaultParams = {
      key: "",
      channelFrom: "",
      overdueDayStart: "",
      overdueDayEnd: "",
      productTypeCodes: [],
      states: [],
      disStates: ["INIT"],
      staffIds: [],
      bizLevel: "",
      batchIds: [],
      riskType: "",
      riskIdentification: "",
      lastBackedDateStart: null,
      lastBackedDateEnd: null,
    }

    // 构建请求参数
    const params: GetCaseListParams = {
      current: 1,
      size: 1000, // 获取足够多的数据
      queryType: 'own',
      disStates: ['INIT'],
      loanCreatedStart: todayStart,
      loanCreatedEnd: todayEnd
    };

    Object.assign(params, defaultParams);
    console.log('请求参数:', params);

    const result = await getCaseList(params);

    if (result.success && result.result) {
      const { records } = result.result;
      const allRecords = records || [];

      // 过滤掉包含『南宁小贷』的批次名称数据
      const filteredRecords = allRecords.filter((record: CaseRecord) => {
        const batchName = record.batchName || '';
        return !batchName.includes('南宁小贷');
      });

      casesData.value = filteredRecords;

      // 设置默认激活的Tab
      if (filteredRecords.length > 0) {
        const firstBatchName = filteredRecords[0].batchName || '未分组';
        activeTabKey.value = firstBatchName;
      }

      console.log('获取分案案件列表成功:', {
        原始记录数: allRecords.length,
        过滤后记录数: filteredRecords.length,
        过滤掉的记录数: allRecords.length - filteredRecords.length,
        批次分组: Object.keys(groupedCases.value),
        今日时间范围: { todayStart, todayEnd }
      });

      message.success(`获取分案案件列表成功，共 ${filteredRecords.length} 条记录（已过滤包含"南宁小贷"的数据）`);
    } else {
      message.error('获取分案案件列表失败');
      casesData.value = [];
    }
  } catch (error) {
    console.error('获取案件列表失败:', error);
    message.error('网络错误，请稍后重试');
    casesData.value = [];
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const handleRefresh = () => {
  fetchEntrustList();
};

// 页面加载时获取数据
onMounted(() => {
  fetchEntrustList();
});

// 分案
const handleEntrust = () => {
  if (isEntrustButtonDisabled.value) return;

  // 获取当前选中行的loanIds
  const selectedLoanIds = selectedRowKeys.value;

  if (selectedLoanIds.length === 0) {
    message.warning('请选择要分案的数据');
    return;
  }

  // 打开分案弹框
  isEntrustModalVisible.value = true;

  // 请求分案初始化数据
  fetchDistributeInitData(selectedLoanIds);
};

// 获取分案初始化数据
const fetchDistributeInitData = async (loanIds: string[]) => {
  try {
    // 构建渠道客户信息
    const channelClients = loanIds.map(loanId => {
      const caseItem = casesData.value.find(item => item.loanId === loanId);
      return {
        channelId: caseItem?.channelFrom || '',
        clientId: caseItem?.clientId || ''
      };
    });

    // 请求分案初始化接口
    const countResult = await countDistributeOne({
      channelClients: channelClients,
      loanScene: 'COLLECTION',
      tsToken: localStorage.getItem('tsToken') || ''
    });

    if (countResult.success && countResult.result) {
      entrustForm.value.validClients = countResult.result.client || 0;
      entrustForm.value.caseCount = countResult.result.case || 0;
      entrustForm.value.errClient = countResult.result.errClient || 0;
      entrustForm.value.channelClients = channelClients;
      entrustForm.value.loanIds = loanIds;
    }

    // 请求组织架构列表
    const orgResult = await getOrgList();

    if (orgResult.success && orgResult.result) {
      orgList.value = orgResult.result || [];
    }

  } catch (error) {
    console.error('获取分案初始化数据失败:', error);
    message.error('获取分案数据失败');
  }
};

// 组织架构变化处理
const handleOrgChange = async (orgId: string) => {
  if (!orgId) {
    userList.value = [];
    entrustForm.value.targetIds = [];
    return;
  }

  try {
    const userResult = await queryUserByOrg({
      object: orgId,
      tsToken: localStorage.getItem('tsToken') || ''
    });

    if (userResult.success && userResult.result) {
      // 转换数据格式：{userId: userInfo} -> [userInfo]
      userList.value = Object.values(userResult.result);
      entrustForm.value.targetIds = []; // 清空已选人员
    }
  } catch (error) {
    console.error('获取组织人员失败:', error);
    message.error('获取组织人员失败');
  }
};

// 分案弹框确认
const handleEntrustConfirm = async () => {
  if (!entrustForm.value.orgId) {
    message.warning('请选择组织架构');
    return;
  }

  if (!entrustForm.value.targetIds || entrustForm.value.targetIds.length === 0) {
    message.warning('请选择组织人员');
    return;
  }

  try {
    // 构建分案参数
    const distributeParams = {
      channelClients: entrustForm.value.channelClients,
      orgIds: [entrustForm.value.orgId],
      targetIds: entrustForm.value.targetIds,
      loanScene: 'COLLECTION',
      tsToken: localStorage.getItem('tsToken') || ''
    };

    console.log('分案参数:', distributeParams);

    // 调用分案接口
    const result = await distributeOne(distributeParams);

    if (result.success) {
      message.success('分案成功');
      isEntrustModalVisible.value = false;

      // 清空复选框
      selectedRowKeys.value = [];
      isEntrustButtonDisabled.value = true;

      // 清空表单数据
      clearFormData();

      // 分案完成后刷新列表
      await fetchEntrustList();

      // 分案完成后执行定时任务
      try {
        const taskSuccess = await executeScheduledTask();
        if (taskSuccess) {
          // 定时任务执行成功后再次刷新列表
          await fetchEntrustList();
        }
      } catch (error) {
        console.error('定时任务执行失败:', error);
        // 定时任务失败不影响分案结果，只记录错误
      }
    } else {
      message.error(result.message || '分案失败');
    }
  } catch (error) {
    console.error('分案失败:', error);
    message.error('分案失败，请稍后重试');
  }
};

// 分案弹框取消
const handleEntrustCancel = () => {
  isEntrustModalVisible.value = false;
  // 清空表单数据
  clearFormData();
};

// 清空表单数据的通用函数
const clearFormData = () => {
  entrustForm.value = {
    validClients: 0,
    caseCount: 0,
    errClient: 0,
    orgId: '',
    targetIds: [],
    channelClients: [],
    loanIds: []
  };
  userList.value = [];
};
</script>

<style scoped>
.entrust-list-container {
  height: 100%;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  box-sizing: border-box;
  overflow: hidden;

  display: flex;
  flex-direction: column;
}

.page-header {
  height: 130px;
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #f0f0f0;
}

.header-title h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 600;
}

.header-title h2 span {
  color: #8c8c8c;
  font-size: 16px;
  font-weight: 400;
  margin-left: 8px;
}

.date-range-info {
  margin: 0 0 16px 0;
  color: #8c8c8c;
  font-size: 14px;
}

.color-legend {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #8c8c8c;
}

.legend-color {
  width: 16px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
}

.today-pending-audit-color {
  background-color: #fff2e8;
  border-left: 3px solid #ff7a00;
}

.today-color {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.yesterday-color {
  background-color: #fff7e6;
  border-left: 3px solid #fa8c16;
}

.recent-color {
  background-color: #f0f5ff;
  border-left: 3px solid #1890ff;
}

.older-color {
  background-color: #fafafa;
  border-left: 3px solid #d9d9d9;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-section {
  height: calc(100% - 154px);
}

.table-wrapper {
  height: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
  border: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
}

.case-count-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: left;
}

.count-item {
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.count-item:first-child {
  color: #1890ff;
  font-weight: 500;
}

/* 今日案件行样式 */
:deep(.today-row) {
  background-color: #f6ffed !important;
  border-left: 4px solid #52c41a;
}

:deep(.today-row:hover) {
  background-color: #f0f9ff !important;
}

/* 今日待审核案件行样式 - 特殊高亮 */
:deep(.today-pending-audit-row) {
  background: linear-gradient(135deg, #fff2e8 0%, #f6ffed 100%) !important;
  border-left: 4px solid #ff7a00;
  box-shadow: 0 2px 8px rgba(255, 122, 0, 0.15);
  position: relative;
}

:deep(.today-pending-audit-row:hover) {
  background: linear-gradient(135deg, #ffe7ba 0%, #f0f9ff 100%) !important;
  box-shadow: 0 4px 12px rgba(255, 122, 0, 0.25);
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 今日待审核案件特殊标识 */
:deep(.today-pending-audit-row::before) {
  content: '⚠️';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  z-index: 1;
}

/* 昨日案件行样式 */
:deep(.yesterday-row) {
  background-color: #fff7e6 !important;
  border-left: 4px solid #fa8c16;
}

:deep(.yesterday-row:hover) {
  background-color: #fffbe6 !important;
}

/* 近3日案件行样式 */
:deep(.recent-row) {
  background-color: #f0f5ff !important;
  border-left: 4px solid #1890ff;
}

:deep(.recent-row:hover) {
  background-color: #e6f7ff !important;
}

/* 更早案件行样式 */
:deep(.older-row) {
  background-color: #fafafa !important;
  border-left: 4px solid #d9d9d9;
}

:deep(.older-row:hover) {
  background-color: #f5f5f5 !important;
}

/* 无日期案件行样式 */
:deep(.no-date-row) {
  background-color: #fff2f0 !important;
  border-left: 4px solid #ff4d4f;
}

:deep(.no-date-row:hover) {
  background-color: #fff1f0 !important;
}

/* 无效日期案件行样式 */
:deep(.invalid-date-row) {
  background-color: #f9f0ff !important;
  border-left: 4px solid #722ed1;
}

:deep(.invalid-date-row:hover) {
  background-color: #f4f0ff !important;
}

/* 表格行悬停效果优化 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: inherit !important;
}


:deep(.ant-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;

  .ant-tabs-nav {
    margin-bottom: 0;
    flex-shrink: 0;
  }

  .ant-tabs-content-holder {
    height: calc(100% - 36px);
    box-sizing: border-box;
    padding: 0;
    overflow: hidden;
  }

  .ant-tabs-tabpane {
    height: 100%;
    padding: 16px;
    box-sizing: border-box;
  }
}

/* 客户信息样式 */
.customer-info {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.customer-name {
  font-weight: 500;
  color: #1a1a1a;
  margin-bottom: 4px;
}

.customer-mobile {
  font-size: 12px;
  color: #666;
}

/* 期数信息样式 */
.period-info {
  text-align: center;
  font-size: 12px;
  line-height: 1.4;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.period-info div {
  margin-bottom: 2px;
}

/* 金额信息样式 */
.amount-info {
  text-align: center;
  font-size: 12px;
  line-height: 1.4;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.amount-info div {
  margin-bottom: 2px;
}

.amount-info div:first-child {
  font-weight: 500;
  color: #ff4d4f;
}

/* Tab样式优化 */
:deep(.ant-tabs-tab) {
  padding: 8px 16px;
  margin-right: 8px;
}

:deep(.ant-tabs-tab-active) {
  background-color: #f0f9ff;
  border-radius: 4px;
}

/* 表格样式优化 */
:deep(.ant-table) {
  height: calc(100% - 36px) !important;
}

:deep(.ant-table-container) {
  height: calc(100% - 36px) !important;
}

:deep(.ant-table-body) {
  overflow-y: auto !important;
  max-height: calc(100vh - 300px) !important;
}

:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  text-align: center;
  vertical-align: middle;
  position: sticky;
  top: 0;
  z-index: 10;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 8px 6px;
  text-align: center;
  vertical-align: middle;
  font-size: 12px;
}

/* 刷新按钮美化 */
:deep(.ant-btn-primary) {
  background-color: #1890ff;
  border-color: #1890ff;
}

:deep(.ant-btn-primary:hover) {
  background-color: #40a9ff;
  border-color: #40a9ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .entrust-list-container {
    padding: 16px;
  }

  .page-header {
    padding: 16px;
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .header-title h2 {
    font-size: 20px;
  }

  .color-legend {
    gap: 12px;
  }

  .legend-item {
    font-size: 12px;
  }
}

/* a-affix 居中样式 */
.affix-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 16px;
}

/* 委案弹框标题居中 */
:deep(.ant-modal-header) {
  text-align: center;
}

:deep(.ant-modal-title) {
  text-align: center;
  font-weight: 600;
}

/* 空数据页面样式 */
.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  padding: 40px 20px;
}

.empty-description {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.empty-tip {
  margin: 8px 0 0 0;
  font-size: 14px;
  color: #999;
  line-height: 1.5;
}

/* 粘性侧边栏样式 */
.sticky-sidebar {
  position: sticky;
  top: 0;
  align-self: flex-start;
  z-index: 10;
}

/* 新布局样式 */
.new-layout {
  display: flex;
  gap: 16px;
}

/* 无数据容器样式 */
.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

/* 侧边栏菜单样式优化 */
.sticky-sidebar :deep(.ant-menu) {
  border-right: none;
}

.sticky-sidebar :deep(.ant-menu-item) {
  margin: 4px 0;
  border-radius: 6px;
}

.sticky-sidebar :deep(.ant-menu-item-selected) {
  background-color: #e6f7ff;
  color: #1890ff;
}

/* 主内容区域样式 */
.w-4\/5 {
  flex: 1;
  min-width: 0;
}

/* 菜单项样式 */
.menu-item-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.menu-checkbox {
  flex-shrink: 0;
}

.menu-label {
  flex: 1;
  font-size: 14px;
  line-height: 1.4;
}

/* 全选菜单项特殊样式 */
:deep(.ant-menu-item[data-menu-id*="select-all"]) {
  background-color: #f0f9ff;
  border-left: 3px solid #1890ff;
  font-weight: 500;
}

:deep(.ant-menu-item[data-menu-id*="select-all"]:hover) {
  background-color: #e6f7ff;
}

/* 选中状态的菜单项样式 */
:deep(.ant-menu-item-selected) {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
}

/* 复选框样式优化 */
:deep(.menu-checkbox .ant-checkbox) {
  margin-right: 0;
}

:deep(.menu-checkbox .ant-checkbox-inner) {
  width: 16px;
  height: 16px;
}

:deep(.menu-checkbox .ant-checkbox-checked .ant-checkbox-inner) {
  background-color: #1890ff;
  border-color: #1890ff;
}
</style>